package com.tanhua.dubbo.utils;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.MovementTimeLine;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 工具类：异步多线程保存时间线数据
 * @author Xiao
 * @date 2021/10/26
 */
@Component
public class TimeLineService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Async  //异步多线程执行方法
    public void saveTimeLine(Long userId, ObjectId movementId) {
        //查询当前用户的好友数据
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        try {
            Thread.sleep(10000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //循环好友数据，构建时间线数据并保存
        List<MovementTimeLine> movementTimeLines = new ArrayList<>();
        for (Friend friend : friends) {
            MovementTimeLine movementTimeLine = new MovementTimeLine();
            movementTimeLine.setMovementId(movementId);
            movementTimeLine.setUserId(friend.getUserId());
            movementTimeLine.setFriendId(friend.getFriendId());
            movementTimeLine.setCreated(System.currentTimeMillis());
//                mongoTemplate.save(movementTimeLine);
            movementTimeLines.add(movementTimeLine);
        }
        mongoTemplate.insertAll(movementTimeLines);
    }

}
